package cn.threewaters.qtyy.config.shiro;

import javax.annotation.Resource;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.mapper.EntityWrapper;

import cn.threewaters.qtyy.dit.one.entity.SysUser;
import cn.threewaters.qtyy.service.sys.SysUserService;

@Component
public class CustomAuthorizingRealm extends AuthorizingRealm {

	@Resource
	private SysUserService sysUserService;
	@Resource
	private CredentialsMatcher credentialsMatcher;

	/**
	 * 授权(验证权限时调用)
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		// SysUser sysUser = (SysUser) principals.getPrimaryPrincipal();
		// String id = sysUser.getId();
		// 用户权限列表
		// Set<String> permsSet = sysMenuService.getUserPermissions(userId);
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		// info.setStringPermissions(permsSet);
		return info;
	}

	/**
	 * 认证(登录时调用)
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		String loginName = (String) token.getPrincipal();

		// 查询用户信息
		SysUser sysUser = sysUserService.selectOne(new EntityWrapper<SysUser>().eq("username", loginName));

		// 账号不存在
		if (sysUser == null) {
			throw new UnknownAccountException("账号或密码不正确");
		}

		// 账号锁定
		if (sysUser.getActiveFlag() == 0) {
			throw new LockedAccountException("账号已被锁定,请联系管理员");
		}

		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(sysUser, sysUser.getPassword(),
				ByteSource.Util.bytes(sysUser.getCredentialsSalt()), getName());
		return info;
	}

}
